package com.ruoyi.auth.utils;

import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 工具类：用于发送短信验证码
 */
public class SmsSender {

    // 配置常量
    private static final String HOST = "https://gyytz.market.alicloudapi.com";
    private static final String PATH = "/sms/smsSend";
    private static final String APPCODE = "97170a76b4ed4ad69179f1449399816f"; // TODO: 替换为真实的AppCode
    private static final String SMS_SIGN_ID = "2e65b1bb3d054466b82f0c9d125465e2";
    private static final String TEMPLATE_ID = "908e94ccf08b4476ba6c876d13f084ad";

    /**
     * 发送短信验证码
     * @param mobile 手机号
     * @return 接口响应字符串
     */
    public static String sendSms(String mobile,String code )throws  Exception {
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("Authorization", "APPCODE " + APPCODE);
        headers.set("X-Ca-Key", APPCODE); // 某些阿里云API需要这个头部
        headers.set("Accept", "application/json");

        // 设置请求参数
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("mobile", mobile);
        params.add("param", "**code**:"+code+",**minute**:10"); // TODO: 换成动态验证码和过期时间
        params.add("smsSignId", SMS_SIGN_ID);
        params.add("templateId", TEMPLATE_ID);

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);


            // 调用API
            ResponseEntity<String> response = restTemplate.exchange(
                    HOST + PATH,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );
            return response.getBody();
    }

    // 示例调用
    public static void main(String[] args) throws Exception{
        // 替换为实际手机号
        String mobile = "18623558089";
        String result = sendSms(mobile,"123456");
        System.out.println("发送结果: " + result);
    }
}